<template>
  <div class="search">
    <div class="head">
      <span class="iconfont iconjiantou2" @click="$router.back()"></span>
      <van-search
        v-model="keyword"
        placeholder="请输入搜索关键词"
        shape="round"
      >
      </van-search>
       <div @click="onSearch(keyword)">搜索</div>
    </div>
    <div class="result1">
      <h2>搜索历史</h2>
      <a href="javascript:;" v-for="(item,index) in historyList" :key="index" @click="onSearch(item)">{{item}}</a>
    </div>
    <div class="result">
      <h2>搜索结果</h2>
      <router-link :to="{path: `/articleDetail/${arti.id}`}" v-for="(arti) in searchList" :key="arti.id">{{arti.title}}</router-link>
    </div>
  </div>
</template>

<script>
import { searchArticle } from '../apis/article.js'
export default {
  data() {
   return {
      keyword:'',
    searchList:[],
      historyList:[]
   }
  },
  mounted() {
// 把本地的搜索历史读出 
this.historyList= JSON.parse(localStorage.getItem('history')||'[]')
  },
  methods: {
  async onSearch(key) {
    console.log(key);
    
    if(key) {
      let res = await searchArticle({
        keyword:key
      })
      if(res.data.data.length > 0) {
        this.searchList = res.data.data;
      }
    }
    // 先读取本地的搜索数据
      let arr = JSON.parse(localStorage.getItem('history')||'[]')
      
      // 判断
      let index = arr.indexOf(key)
      if(index !== -1) {
        arr.splice(index,1)
      }else {
        arr.unshift(key)
        localStorage.setItem('history',JSON.stringify(arr))
      }
    this.historyList= JSON.parse(localStorage.getItem('history')||'[]')
    }
  }
};
</script>

<style lang="less" scoped>
.head {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #000;
  padding: 0 10px;
  padding: 8px 12px;
  .van-search {
    padding: 5px 12px;
    flex: 1;
  }
}
.result,
.result1 {
  padding: 20px;
  border-bottom: 1px solid #ccc;
  h2 {
    padding: 10px 0;
  }
a {
  padding: 5px;
  display: block;
}
}
</style>